from typing import Union
from sqlalchemy.orm import Session
from .. import models, schemas

# 班级操作
def create_class(db: Session, Class: schemas.Classes_Create):
    db_class = models.Classes(
        name=Class.name,
        enabled=1
    )
    db.add(db_class)
    db.commit()
    db.refresh(db_class)
    return db_class

def get_class(db: Session, name: str) -> Union[models.Classes, None]:
    return db.query(models.Classes).filter(models.Classes.name == name).first()

def get_classes(db: Session, limit: int, offset: int):
    return db.query(models.Classes).limit(limit).offset(offset).all()

def update_classes(db: Session, update_class: schemas.Classes_Update):
    if update_class.id:
        update_db = db.query(models.Classes).filter(models.Classes.id == update_class.id)
    elif update_class.old_name:
        update_db = db.query(models.Classes).filter(models.Classes.name == update_class.old_name)
    if not update_db.one():
        return None
    if update_class.new_name:
        update_db.update({'name': update_class.new_name})
    elif update_class.new_enabled:
        update_db.update({'enabled': update_class.new_enabled})
    db.commit()
    return update_db

# 连接班级操作
def create_user_class(db: Session, user_id: int, classes_id: int):
    db_user_class = models.User_Class(
        users_id=user_id,
        classes_id=classes_id
    )
    db.add(db_user_class)
    db.commit()
    db.refresh(db_user_class)
    return db_user_class

def get_user_class(db: Session, user_id: int) -> list[schemas.User_Class]:
    return db.query(models.User_Class).filter(models.User_Class.users_id == user_id).one()
